import StandModal from '@/components/StandModal';
import UnusualContain from '@/pages/mainPages/unusualContain';
import { debounce, debounceDelay, hasBottomHeight } from '@/utils/helper';
import { checkDistributionWay, DistributionWayStatus } from './orgView/helper';
import { useShowLoading } from '@/utils/hooks/useShowLoading';
import utils from '@/utils/index';
import { View, ScrollView } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import CartAddress from './cartAddress';
import EmptyCart from './EmptyCart';
import styles from './index.module.scss';
import { ExpiredArea, OverDistributionArea } from './InvalidArea';
import OrgView from './orgView';
import SumPriceBottom from './orgView/SumPriceBottom';

const OrgList = ({ orgList, onDelete, onProductNumChange }) => {
  return (
    <>
      {orgList?.map((org) => {
        return (
          <OrgView
            key={org.orgId}
            {...{
              org,
              onDelete,
              onProductNumChange,
            }}
          />
        );
      })}
    </>
  );
};

const CartOrgList = ({
  unusualInfo,
  isLoading,
  currentLocation,
  cartList,
  invalidList,
  orgOverDistributionList,

  onDelete,
  onBatchDelete,
  onProductNumChange,
}) => {
  // 接口出错, 需要刷新
  if (unusualInfo) {
    return <UnusualContain unusualInfo={unusualInfo} />;
  }

  // 未登录
  if (!utils.getToken()) {
    return <EmptyCart />;
  }

  // 无购物车数据
  if (
    !isLoading &&
    currentLocation &&
    !cartList?.length &&
    !invalidList?.length &&
    !orgOverDistributionList?.length
  ) {
    return <EmptyCart />;
  }

  // 显示购物车数据
  return (
    <View className="wrap">
      <OrgList {...{ orgList: cartList, onDelete, onProductNumChange }} />

      <ExpiredArea productList={invalidList} onDelete={onBatchDelete} />

      <OverDistributionArea orgList={orgOverDistributionList} onDelete={onBatchDelete} />
    </View>
  );
};

const CartPage = ({
  dispatch,
  loading,
  cartSelectedChange,
  cartList,
  invalidList,
  orgOverDistributionList,
  allProducts,
  cartSelected,
  cartNoMenu = false,
  taihujishi = false,
  noMenu = false,
  back = false,
}) => {
  const isLoading = useShowLoading(loading);
  noMenu = noMenu || cartNoMenu;
  const unusualInfo = utils.getLocalStorage('unusualInfo');
  const [currentLocation, setCurrentLocation] = useState();
  const [showCartAddress, setshowCartAddress] = useState(false)

  const [selectData,setSeleData] = useState([])
  useEffect(()=>{
    let arr = []
    allProducts?.map(res=>{
      if(res.selected){
        arr.push(res)
      }
    })
    setSeleData(arr)
  },[allProducts])
  // 删除商品确认框数据
  const [removeCartIds, setRemoveCartIds] = useState();
  const [showRemove,setShowRemove] = useState(false)

  const getList = useCallback(
    async (from) => {
      return dispatch({
        type: 'productCar/getCartList',
        payload: {
          ...currentLocation,
          ...cartSelectedChange,
        },

        from: noMenu ? 'cartSin' : 'standardCartPage',
      });
    },
    [currentLocation, cartSelectedChange],
  );

  // 删除商品
  const onDelete = debounce(async (goods) => {
    let { id } = goods;
    await dispatch({ type: 'productCar/deleteDeleteProduct', payload: { id } });
    await getList('onDelete');
  }, 300);

  // 批量删除商品
  const onBatchDelete = debounce(async (cartProductsOrIds) => {
    if (!cartProductsOrIds?.length) {
      return;
    }

    if (typeof cartProductsOrIds[0] !== 'string') {
      cartProductsOrIds = cartProductsOrIds.map(({ id }) => {
        return id;
      });
    }
    setShowRemove(true)
    setRemoveCartIds(cartProductsOrIds);
  }, 300);

  const onRemoveProductsClose = () => {
    setShowRemove(false)
    setRemoveCartIds();
  };

  const onRemoveProductsOk = async (cartIds) => {
    onRemoveProductsClose();

    await dispatch({
      type: 'productCar/batchDeleteProducts',
      payload: { carIds: cartIds },
    });

    await getList('onRemoveProductsOk');
  };

  // 更新商品数量
  const onProductNumChange = useMemo(
    () =>
      debounceDelay(async (id, num) => {
        await dispatch({
          type: 'productCar/updateProductNum',
          payload: { id, num },
        });

        await getList('onProductNumChange');
      }, 500),
    [getList],
  );

  // 清除 未使用的信息
  useDidShow(() => {
    if (utils.getLocalStorage('unusualInfo')) {
      utils.setLocalStorage('unusualInfo', '');
    }
  });

  // // 获取购物车列表
  // useDidShow(() => {
  //   // 未登录
  //   if (!utils.getToken()) {
  //     return;
  //   }

  //   getList('useDidShow');
  // });

  // 重新获取商品
  useEffect(() => {
    // 未登录
    if (!utils.getToken()) {
      return;
    }

    getList('useEffect[getList]');
  }, [getList]);

  // 获取购物车数量
  useDidShow(() => {
    dispatch({
      type: 'productList/getCarNum',
      payload: {},
    });
  });

  // 设置下标题
  useEffect(() => {
    utils.setTitle('购物车');
  }, []);

  // 太湖吉市 底部高度
  const baseHeight = useMemo(() => {
    if (taihujishi) {
      return 130;
    }

    return 100;
  }, [taihujishi]);

  const bottomHeight = useMemo(() => {
    return noMenu ? 0 : hasBottomHeight() ? baseHeight + 66 : baseHeight;
  }, [noMenu, baseHeight]);

  // 太湖吉市 设置底部状态栏
  useDidShow(() => {
    if (taihujishi) {
      Taro.setTabbarIndex(1);
    }
  });

  // 去购买
  const handleBuy = () => {
    if (!selectData.length) {
      return Taro.showToast({
        mask: true,
        title: '最少购买1件',
        image: failImg,
        duration: 1000,
      });
    }

    const group = checkDistributionWay(selectData);

    if (group === DistributionWayStatus.emptySet) {
      Taro.showToast({
        title: '商品未配置配送方式，请联系商家处理',
        icon: 'none',
        duration: 3000,
      });
      return;
    }

    if (group === DistributionWayStatus.intersection) {
      goToBuy(selectData);
      return;
    }

    setDistributionWayGroup(group);
  };
  const goToBuy = (productList) => {
    const cartIds = productList.map((v) => v.id);
    const productReleaseIds = productList.map(({ productReleaseId }) => productReleaseId);

    dispatch({
      type: 'productCar/setCartShopSelected',
      payload: cartIds,
    });

    dispatch({
      type: 'productCar/setCartShopProductReleaseIds',
      payload: productReleaseIds,
    });

    Taro.navigateTo({
      url: `/orderSubPack/confirmOrder/index`,
    });
  };
  const changeCartSelect = (ids, curSelectedStatus) => {
    let idList = [];
    if (Array.isArray(ids)) {
      idList = ids;
    } else {
      idList = [ids];
    }
    if (curSelectedStatus) {
      dispatch({
        type: 'productCar/setCartSelectedChange',
        payload: { unChooseIds: idList },
      });
    } else {
      dispatch({
        type: 'productCar/setCartSelectedChange',
        payload: { chooseIds: idList },
      });
    }
  };

  const toggleOrg = () => {
    if (selectData?.length === allProducts?.length) {
      changeCartSelect(cartSelected, true);
    } else {
      changeCartSelect(cartSelected, false);
    }
  };
  return (
    <View
      className={styles.Cart}
      style={{
        height: utils.getCalcHeight({}, bottomHeight),
      }}
    >
      <StandModal {...{
          isOpened: showRemove && removeCartIds?.length > 0,

          cancelText: '取消',
          onClose: onRemoveProductsClose,

          confirmText: '删除',
          onConfirm: () => {
            onRemoveProductsOk(removeCartIds);
          },

          content: removeCartIds?.length ? `确认删除${removeCartIds?.length}件商品？` : '',
        }}
      />

      <ScrollView
        scrollY
        style={{
          height: utils.getCalcHeight({ topMenuHeight: true }, bottomHeight),
        }}
      >
        {utils.getToken() && <CartAddress onChange={setCurrentLocation} onShowModal={e=>{
          setshowCartAddress(e)
        }} />}

        <CartOrgList
          {...{
            unusualInfo,
            isLoading,
            currentLocation,
            cartList,
            invalidList,
            orgOverDistributionList,
            onDelete,
            onBatchDelete,
            onProductNumChange,
          }}
        />
      </ScrollView>
      {showCartAddress?null:
      <SumPriceBottom
        {...{
          totalPrice: selectData?.reduce((pre,next)=>{
            return pre += (next.price*next.num)
          },0),
          totalDiscountAmount: 0,
          handleBuy,
          shopSelected: selectData,
          isOpened: false,
          onSelect: toggleOrg,
          isAllSelected: selectData?.length === allProducts?.length,
        }}
      />}
    </View>
  );
};

export default connect(({ loading, productCar }) => ({
  loading,
  cartList: productCar.cartList,
  invalidList: productCar.invalidList,
  orgOverDistributionList: productCar.orgOverDistributionList,
  stockLimitList: productCar.stockLimitList,
  selectedAddress: productCar.selectedAddress,
  cartSelectedChange: productCar.cartSelectedChange,
  allProducts: productCar.allProducts,
  cartSelected:productCar.cartSelected,
}))(CartPage);
